<template>
    <div class="e-table">
        <div class="top" v-if="attachTableData.length || (!attachTableData.length && !isView)">
            <div class="left">
                <el-upload
                    v-if="!isView"
                    class="upload-demo"
                    :action="uploadUrl"
                    :headers="{
                        token: userInfo.token,
                        org: encodeURIComponent(JSON.stringify(userInfo.orgInfo))
                    }"
                    :data="{
                        bucketName,
                        relationId,
                        orgCode
                    }"
                    :before-upload="beforeAvatarUpload"
                    multiple
                    :accept="accept"
                    :on-progress="attachProgress"
                    :on-success="attachOnSuccess"
                    :on-change="attachOnChange"
                    :show-file-list="false"
                    name="files"
                >
                    <el-button size="small" class="btn-greenYellow"> 上传附件 </el-button>
                </el-upload>
                <el-button
                    size="small"
                    class="btn-greenYellow"
                    v-if="!isView"
                    @click="attachDownload"
                    >批量下载</el-button
                >
                <el-button
                    slot="reference"
                    size="small"
                    class="btn-delete"
                    v-if="!isView"
                    @click="deleteData"
                    >批量删除</el-button
                >
                <span style="margin: 0 0 0 10px; color: #999; line-height: 35px" v-if="!isView"
                    >*仅支持上传图片、PDF格式，文件小于20M</span
                >
            </div>
        </div>
        <el-table
            :data="attachTableData"
            border
            style="width: 100%"
            @cell-mouse-enter="cellMouseEnter"
            @cell-mouse-leave="cellMouseLeave"
            @selection-change="attachSelectionChange"
            ref="attach"
            v-sortTable="{ tableData: attachTableData, _this: this, ref: 'attach' }"
            class="table"
            :key="key"
        >
            <el-table-column show-overflow-tooltip type="selection" width="55" v-if="!isView">
            </el-table-column>
            <el-table-column label="操作" fixed width="100px" align="left">
                <template slot-scope="{ row }">
                    <div class="oparation_box">
                        <img
                            src="@/assets/btn/downLoad.png"
                            class="add_sub"
                            @click="downloadFile(row)"
                            title="下载"
                        />
                        <!-- 在第一次审核中，当前审核人上传了附件信息，到下一审核人，审核时，能把上一个审核人上传的附件给删除了，这是错误的，需要修改 -->
                        <img
                            src="@/assets/btn/delete.png"
                            class="cancel_delete"
                            @click="deleteEle(row)"
                            v-if="!isView && curUserName === row.userName"
                            title="删除"
                        />
                        <img
                            src="@/assets/btn/preview.png"
                            class="add_preview"
                            @click="previewFile(row)"
                            title="预览"
                        />
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                show-overflow-tooltip
                prop="nonIPObjectPath"
                width="200"
                label="缩略图"
            >
                <template slot-scope="{ row }" :size="60">
                    <div style="display: flex; justify-content: center">
                        <el-image
                            v-if="
                                'jpg,jpeg,png'.includes(
                                    row.objectName.split('.').pop().toLowerCase()
                                )
                            "
                            style="width: 30px; height: 30px"
                            :src="oss + row.nonIPObjectPath"
                            :preview-src-list="imageList"
                        ></el-image>
                        <el-image v-else style="width: 30px; height: 30px" :src="pdfImg"></el-image>
                    </div>
                </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="objectName" label="文件名称">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="objectSize" label="文件大小" width="120">
                <template slot-scope="{ row }">
                    {{ bytesToSize(row.objectSize) }}
                </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="gmtCreate" width="200" label="上传时间">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="userName" width="120" label="上传人">
            </el-table-column>
            <div class="upload" slot="empty" v-if="!isView">
                <!-- 机构简码暂时写死 orgCode: $store.state.userInfo.orgInfo.shortCode -->
                <!-- orgCode: 'DQGSGJGSZCB1-1' -->
                <el-upload
                    class="upload-demo"
                    drag
                    :action="uploadUrl"
                    :headers="{
                        token: userInfo.token,
                        org: encodeURIComponent(JSON.stringify(userInfo.orgInfo))
                    }"
                    :data="{
                        bucketName,
                        relationId,
                        orgCode
                    }"
                    :before-upload="beforeAvatarUpload"
                    multiple
                    :accept="accept"
                    :on-success="attachOnSuccess"
                    :show-file-list="false"
                    name="files"
                >
                    <el-button type="primary" style="padding: 20px 80px">上传附件</el-button>
                    <div style="margin-top: 10px; line-height: 25px; font-size: 12px">
                        鼠标拖入上传，按住Ctrl可多选附件<br />
                        *仅支持上传图片、PDF格式，文件小于20M
                    </div>
                </el-upload>
            </div>
        </el-table>

        <com-pagination
            v-if="attachTableData.length !== 0"
            :total="total"
            :pageSize.sync="pageSize"
            :currentPage.sync="currentPage"
            :tableData.sync="attachTableData"
        />
    </div>
</template>
<script>
import service from '@/utils/request'
import { oss } from '@/utils/request'
import ossRequest from '@/api/oss/oss'
import ComPagination from '@/components/pagination/pagination'
import { bytesToSize, showLoading, hideLoading, batchDownload } from '@/utils/common'
import pdfImg from '@/assets/pdf_icon.png'
import { mapState } from 'vuex'

export default {
    props: {
        bucketName: {
            type: String,
            default: '',
            require: true
        },
        relationId: {
            type: String,
            default: '',
            require: true
        },
        isView: {
            type: Boolean,
            default: false
        }
    },
    components: {
        ComPagination
    },
    data () {
        return {
            uploadUrl: 'api/oss/uploader',
            attachTableData: [],
            attachSelection: [],
            pageSize: 10, // 每页显示条目个数
            currentPage: 1,
            total: 0,
            accept: '.jpg,jpeg,.png,.pdf',
            pdfImg,
            oss: oss,
            key: 0
        }
    },
    computed: {
        ...mapState(['userInfo']),
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        },
        // attachTableDataShow () {
        //     const start = (this.currentPage - 1) * this.pageSize
        //     return this.attachTableData.slice(start, start + this.pageSize)
        // }
        imageList () {
            return this.attachTableData
                .filter(row =>
                    'jpg,jpeg,png'.includes(row.objectName.split('.').pop().toLowerCase())
                )
                .map(x => oss + x.nonIPObjectPath)
        },
        curUserName () {
            return localStorage.getItem('userName')
        }
    },
    async created () {
        showLoading()
        this.getObjectByRelationId()
        hideLoading()
    },
    methods: {
        deleteData () {
            const length = this.attachSelection.length
            if (length === 0) return
            this.clientPop('info', this.moreDeleteErr(length), this.attachDel)
        },
        deleteEle (row) {
            const fn = row => {
                return () => {
                    this.attachDel(row)
                }
            }
            this.clientPop('info', this.oneDeleteErr, fn(row))
        },
        attachDownload () {
            const fileList = this.attachSelection.map(item => {
                return {
                    objectName: item.objectName,
                    objectPath: item.objectPath
                }
            })
            batchDownload(fileList)
            // const promiseArr = []
            // this.attachSelection.forEach(item => {
            //     promiseArr.push(this.downloadFile(item))
            // })
            // Promise.all(promiseArr)
        },
        attachSelectionChange (selection) {
            this.attachSelection = selection
        },
        attachDel (row) {
            let recordIds
            if (row) {
                recordIds = [row].map(value => value.recordId)
            } else {
                recordIds = this.attachSelection.map(value => value.recordId)
            }
            const promiseArr = []
            showLoading()
            recordIds.forEach(value => {
                promiseArr.push(ossRequest.deleterRecordId({ recordId: value }))
            })
            Promise.all(promiseArr)
                .then(() => {
                    this.clientPop('suc', '删除成功', this.getObjectByRelationId)
                })
                .catch(() => {
                    this.clientPop('err', '部分数据删除失败', this.getObjectByRelationId)
                })
                .finally(() => {
                    hideLoading()
                })
        },
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20
            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest
                .getObjectByRelationId({ relationId: this.relationId })
                .then(res => {
                    this.attachTableData = res
                    this.total = res.length
                    this.key++ // 修复图片过大时，操作列错误
                    hideLoading()
                })
                .catch(() => {
                    hideLoading()
                })
        },
        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        cellMouseEnter () {},
        cellMouseLeave () {},
        cellClsNm () {
            return ''
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        downloadIamge (imgsrc, fileName) {
            //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {
                    // if browser is IE
                    navigator.msSaveBlob(url.src, url.name) //filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        async downloadFile (obj) {
            showLoading()
            const url = oss + obj.nonIPObjectPath
            const fileNameFull = obj.originalObjectName
            const fileExt = fileNameFull.split('.').pop()
            if (['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(fileExt.toLowerCase()) === -1) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
            hideLoading()
        },
        attachProgress () {
            showLoading('上传中...')
        },
        attachOnChange () {
            hideLoading()
        },
        previewFile (row) {
            window.open(row.objectPath)
        }
    }
}
</script>
<style lang="scss" scoped>
.e-table {
    background-color: auto;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 10px 0 0;
}
</style>
